﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using InvestmentIntelligence.DbModel.Models;

namespace InvestmentIntelligence.Data.Repository.EFImplementation
{
    public class TradeUpdateRepository : IIPRepository<TradeUpdate>, ITradeUpdateRepository
    {
        public Dictionary<int, DateTime> GetUpdateDates(int id)
        {
            if (id == 0)
            {
                return InternalGet(dc =>
                {
                    var context = ((IObjectContextAdapter)dc).ObjectContext;
                    context.CommandTimeout = 0;

                    return (from trade in dc.Trades
                            group trade by trade.FundBookEntityId
                            into fundBookTrades
                            select new
                            {
                                Id = fundBookTrades.Key,
                                Value = fundBookTrades.Min(c => c.Date)
                            });
                }
                , t => t.ToDictionary(k => k.Id, v => v.Value.Date));
            }
            return InternalGet(dc =>
            {
                var context = ((IObjectContextAdapter)dc).ObjectContext;
                context.CommandTimeout = 0;

                return (from tradeUpdate in dc.TradeUpdates            
                                     where tradeUpdate.Id > id
                                     group tradeUpdate by tradeUpdate.FundBookEntityId
                                         into fundBookTrades
                                         select new
                                                    {
                                                        Id = fundBookTrades.Key,
                                                        Value = fundBookTrades.Min(c => c.TradeDate)
                                                    });
            }
            , t => t.ToDictionary(k => k.Id, v => v.Value.Date));
        }

        public int GetLastProcessedItem()
        {
            return Get(v => v.Max(c => (int?)c.Id)).GetValueOrDefault();
        }
    }
}
